//
//  XZMyMessageResultVC.m
//  Teecloud
//
//  Created by PC on 2018/11/13.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZMyMessageResultVC.h"
#import "XZMyMessageSearchVC.h"
#import "XZMyMessageCell.h"
#import "XZMsgList.h"
#import "GMVoiceListModel.h"
#import "GMBuyVideoVC.h"
#import "XZPopCommentVC.h"
#import "GMBuyFile.h"
#import "GMReadPDFVC.h"
#import "XZSearchBar.h"
#import "GMPlayerViewController.h"
@interface XZMyMessageResultVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) XZSearchBar *searchBar;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end
#define MESSAGECELL @"XZMyMessageCell"
@implementation XZMyMessageResultVC

#pragma mark - LifeCycle
- (void)dealloc{
    XZLog(@"%s",__FUNCTION__);
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的消息";
    self.view.backgroundColor = kWhiteColor;
    [self creatTitleView];
    [self GetMsgList];
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    [self GetMsgList];
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.key = searchBar.text;
    [searchBar resignFirstResponder];
}

- (void)creatTitleView{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    //设置titleview，不过这个view并不是我们需要的居中的view；
    self.navigationItem.titleView = titleView;
    __weak typeof(self) weakSelf = self;
    //主线程列队一个block， 这样做 可以获取到autolayout布局后的frame，也就是titleview的frame。在viewDidLayoutSubviews中同样可以获取到布局后的坐标
    __block XZSearchBar *searchBar;
    dispatch_async(dispatch_get_main_queue(), ^{
        //要居中view的宽度
        CGFloat width = 240;
        //实际居中的view
        UIView *centerView = [[UIView alloc]init];
        centerView.backgroundColor = kClearColor;
        //设置一个基于window居中的坐标
        centerView.frame = CGRectMake((DEVICE_WIDTH-width)/2, 20+(kIs_iPhoneX?24:0), width, 44);
        //坐标系转换到titleview
        centerView.frame = [weakSelf.view.window convertRect:centerView.frame toView:weakSelf.navigationItem.titleView];
        searchBar = [[XZSearchBar alloc]initWithFrame:CGRectMake(0, 10, 240, 30)];
        searchBar.delegate = self;
        searchBar.placeholder = self.key;
        searchBar.tintColor = kBlueColor;
        [centerView addSubview:searchBar];
        self.searchBar = searchBar;
        //centerview添加到titleview
        [weakSelf.navigationItem.titleView addSubview:centerView];
    });
}

#pragma mark - MJRefresh
- (void)GetMsgList{
    self.page = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.page) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=GetMsgList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.dataSource removeAllObjects];
                NSArray *array = [XZMsgList mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource addObjectsFromArray:array];
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                if (weakself.dataSource.count == 0) {
                    [weakself.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tableView reloadData];
            }else{
                
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (void)GetMoreMsgList{
    self.page ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.page) forKey:@"pageIndex"];
    [dict setValue:self.key forKey:@"key"];
    
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=GetMsgList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZMsgList mj_objectArrayWithKeyValuesArray:dataInfo];
                [weakself.dataSource addObjectsFromArray:newsArray];
                if (dataInfo.count>0) {
                    [weakself.tableView.mj_footer endRefreshing];
                    [weakself.tableView.mj_header endRefreshing];
                    [weakself.tableView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                }
                
            }else{
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tableView.mj_footer endRefreshing];
            [weakself.tableView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.tableView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    XZMsgList *model = self.dataSource[indexPath.row];
    XZMyMessageCell *messageCell = [tableView dequeueReusableCellWithIdentifier:MESSAGECELL forIndexPath:indexPath];
    messageCell.model = model;
    messageCell.parentController = self;
    //Action
    messageCell.ActionBlock = ^(XZMsgList * _Nonnull model) {
        [weakself actionActionSkipWithModel:model];
    };
    //Attachment.ResName
    messageCell.ResNameBlock = ^(NSInteger tag, XZMsgList * _Nonnull model) {
        [weakself resNameBlock:tag model:model];
    };
    //播放
    messageCell.PostionLoactionBlock = ^(NSInteger tag, XZMsgList * _Nonnull model) {
        [weakself positionBlock:tag model:model];
    };
    messageCell.hasReadBlock = ^(NSInteger index, NSString * _Nonnull voiceID, NSString * _Nonnull voiceStr) {
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"voiceId":voiceID,
                              };
        [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
        [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"v30.teecloud.cn/ajax-api.ashx?$c=TeeyunApp&$m=PostVoiceReadStatus&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
            [MBProgressHUD hideHUDForView:weakself.view animated:YES];
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                    if ([voiceStr isEqualToString:@"MSG"]) {
                        //MsgBody.VoiceList
                        for (NSInteger i=0; i<model.MsgBody.VoiceList.count; i++) {
                            GMVoiceListModel *temModel = model.MsgBody.VoiceList[i];
                            if (i == index) {
                                temModel.IsReaded =YES;
                            }
                        }
                    }else{
                        //Quote.VoiceList
                        for (NSInteger i=0; i<model.Quote.VoiceList.count; i++) {
                            GMVoiceListModel *temModel = model.Quote.VoiceList[i];
                            if (i == index) {
                                temModel.IsReaded =YES;
                            }
                        }
                    }
                    [weakself.tableView reloadData];
                }else{
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
                }
            }else{
                [MBProgressHUD showErrorOrSuc:@"请求出错" toView:weakself.view];
            }
        }];
    };
    return messageCell;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    XZMsgList *model = self.dataSource[indexPath.row];
    return model.cellHeight;
}
#pragma mark - cell的跳转
/**
 点击文字的跳转
 msg.tag = 100,quote = 101
 @param tag 按钮的tag
 @param model 模型
 */
- (void)resNameBlock:(NSInteger)tag model:(XZMsgList *)model{
    if (tag == 100) {//Msg
        NSInteger resType = [model.MsgBody.Attachment.ResType integerValue];
        if (resType == 1) {
            if (!model.MsgBody.Attachment.IsFree) {
                GMBuyVideoVC *buy = [[GMBuyVideoVC alloc] init];
                buy.ResType  = model.MsgBody.Attachment.ResType;
                buy.resId = model.MsgBody.Attachment.ResId;
                [self.navigationController pushViewController:buy animated:YES];
            }else{
                GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
                play.resId = model.MsgBody.Attachment.ResId;
                [self.navigationController pushViewController:play animated:YES];
            }
            
        }else if (resType == 2){
            if (!model.MsgBody.Attachment.IsFree) {
                GMBuyFile *buy = [[GMBuyFile alloc] init];
                buy.ResType  = model.MsgBody.Attachment.ResType;
                buy.resId =  model.MsgBody.Attachment.ResId;
                [self.navigationController pushViewController:buy animated:YES];
            }else{
                GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
                file.resId =  model.MsgBody.Attachment.ResId;
                [self.navigationController pushViewController:file animated:YES];
            }
        }
    }else if (tag == 101){//Quote
        NSInteger resType = [model.Quote.Attachment.ResType integerValue];
        if (resType == 1) {
            if (!model.Quote.Attachment.IsFree) {
                GMBuyVideoVC *buy = [[GMBuyVideoVC alloc] init];
                buy.ResType  = model.Quote.Attachment.ResType;
                buy.resId = model.Quote.Attachment.ResId;
                [self.navigationController pushViewController:buy animated:YES];
            }else{
                GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
                play.resId = model.Quote.Attachment.ResId;
                [self.navigationController pushViewController:play animated:YES];
            }
        }else if (resType == 2){
            if (!model.MsgBody.Attachment.IsFree) {
                GMBuyFile *buy = [[GMBuyFile alloc] init];
                buy.ResType  = model.Quote.Attachment.ResType;
                buy.resId =  model.Quote.Attachment.ResId;
                [self.navigationController pushViewController:buy animated:YES];
            }else{
                GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
                file.resId =  model.Quote.Attachment.ResId;
                [self.navigationController pushViewController:file animated:YES];
            }
        }
    }
    
}

/**
 点击播放时间的跳转
 msg.tag = 102,quote.tag = 103
 @param tag 按钮的tag
 @param model model
 */
- (void)positionBlock:(NSInteger)tag model:(XZMsgList *)model{
    if (tag == 102) {//Msg
        if (!model.MsgBody.Attachment.IsFree) {
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.resId = model.MsgBody.Attachment.ResId;
            [self.navigationController pushViewController:play animated:YES];
        }else{
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.playSecond = [model.MsgBody.Attachment.Position integerValue];
            play.resId = model.MsgBody.Attachment.ResId;
            [self.navigationController pushViewController:play animated:YES];
        }
    }else if (tag == 103){//Quote
        if (!model.Quote.Attachment.IsFree) {
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.resId = model.Quote.Attachment.ResId;
            [self.navigationController pushViewController:play animated:YES];
        }else{
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.playSecond = [model.Quote.Attachment.Position integerValue];
            play.resId = model.Quote.Attachment.ResId;
            [self.navigationController pushViewController:play animated:YES];
        }
    }
    
}

/**
 Action操作按钮的相应事件
 
 @param model 操作按钮
 */
- (void)actionActionSkipWithModel:(XZMsgList*)model{
    XZPopCommentVC *commentVC = [[XZPopCommentVC alloc] init];
    commentVC.model = model;
    [self.navigationController presentSemiViewController:commentVC withOptions:@{
                                                                                 KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                 KNSemiModalOptionKeys.animationDuration : @(0.5),
                                                                                 KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                 }];
}
#pragma mark - Setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.showsVerticalScrollIndicator = false;
        _tableView.showsHorizontalScrollIndicator = false;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([XZMyMessageCell class]) bundle:nil] forCellReuseIdentifier:MESSAGECELL];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(GetMsgList)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(GetMoreMsgList)];
        _tableView.mj_footer.hidden =YES;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}



@end
